package com.zmn.oms.zmn.business.impl.work;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.zmn.base.common.data.common.dro.brand.BrandDRO;
import com.zmn.base.common.data.dubbo.interfaces.brand.BrandListRemoteService;
import com.zmn.base.product.common.consts.BaseProductConsts;
import com.zmn.base.product.common.dto.categ.CategProductGroupDRO;
import com.zmn.base.product.common.dto.product.ProductBaseQuery;
import com.zmn.base.product.common.dto.product.ec.DefaultEcProductQuery;
import com.zmn.base.product.common.dto.product.ec.ProductBaseDRO;
import com.zmn.base.product.common.query.categ.CategProductGroupQuery;
import com.zmn.base.product.dubbo.interfaces.categ.serv.CategServProductListRemoteService;
import com.zmn.base.product.dubbo.interfaces.product.foreign.ProductForeignListRemoteService;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.manager.redis.RedisManager;
import com.zmn.oms.business.interfaces.product.OrderProductExtendBService;
import com.zmn.oms.business.interfaces.serviceitem.OrderServiceItemBService;
import com.zmn.oms.business.interfaces.servtype.ServItemBService;
import com.zmn.oms.common.annotation.ZsNormalOrderWorkLog;
import com.zmn.oms.common.constant.*;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.dto.changerecord.ChangeServCategDTO;
import com.zmn.oms.model.dto.work.masterwork.ModifyProductDTO;
import com.zmn.oms.model.dto.work.modify.CheckQuotationTypeOrderDTO;
import com.zmn.oms.model.dto.work.modify.ProductTaraiffIdDTO;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.masterworking.MasterWorking;
import com.zmn.oms.model.entity.member.OrderMember;
import com.zmn.oms.model.entity.product.OrderProduct;
import com.zmn.oms.model.entity.product.OrderProductExtend;
import com.zmn.oms.model.entity.quotation3.OrderQuotationProcess;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.changerecord.OrderChangeRecordService;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.masterworking.MasterWorkingService;
import com.zmn.oms.services.interfaces.member.OrderMemberService;
import com.zmn.oms.services.interfaces.product.OrderProductService;
import com.zmn.oms.services.interfaces.quotation3.OrderQuotationProcessService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.business.interfaces.quotation3.OrderQuotation3ModifyBService;
import com.zmn.oms.zmn.business.interfaces.work.OrderWorkModifyProductBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkBService;
import com.zmn.oms.zmn.business.interfaces.work.customwork.ZsCustomWorkBService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 类描述
 *
 * @author sunlife
 * @version 1.0
 * @date 2019/9/5 16:12
 */
@Slf4j
@Service
public class OrderWorkModifyProductBServiceImpl implements OrderWorkModifyProductBService {

    /**
     * 工程师修改产品次数保存时间，单位/秒
     */
    public final static int MASTER_MODIFY_PRODUCT_COUNT_SECOND = 86400;
    /**
     * 工程师修改产品次数
     */
    public final static int MASTER_MODIFY_PRODUCT_COUNT = 1;

    @Autowired
    OrderWorkService orderWorkService;
    @Autowired
    MasterWorkingService masterWorkingService;
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    OrderProductService orderProductService;
    @Autowired
    ZsCustomWorkBService zsCustomWorkBService;
    @Autowired
    OrderServiceItemBService orderServiceItemBService;
    @Autowired
    OrderProductExtendBService orderProductExtendBService;
    @Autowired
    ZsOrderWorkBService zsOrderWorkBService;
    @Autowired
    OrderMemberService orderMemberService;
    @Resource
    private RedisManager redisManager;
    @Autowired
    private ServItemBService servItemBService;
    @Autowired
    private OrderQuotationProcessService orderQuotationProcessService;
    @Autowired
    private OrderQuotation3ModifyBService orderQuotation3ModifyBService;
    @Autowired
    private OrderChangeRecordService orderChangeRecordService;


    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
    protected ProductForeignListRemoteService productForeignListRemoteService;
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
    protected CategServProductListRemoteService categServProductListRemoteService;
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
    protected BrandListRemoteService brandListRemoteService;


    /**
     * 工程师修改工单产品
     *
     * @param modifyProductDTO
     */
    @Override
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_MODIFY_PRODUCT, beforeProceed = false)
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderProductByMaster(ModifyProductDTO modifyProductDTO) throws OmsBaseException {
        OrderWork orderWork = orderWorkService.findMasterWorkDetail(modifyProductDTO.getOrderId(),
                modifyProductDTO.getWorkId(), modifyProductDTO.getMasterId());
        if (orderWork == null) {
            throw new OmsBaseException(OrderFailConsts.FAIL_DATA_CHANGE_ORDER_NOMASTER, "无效的工单");
        }

        if (Objects.equals(orderWork.getStatus(), OrderStatusConsts.WORK_STATUS_COMPLETE) ||
                !Objects.equals(orderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_DOING)) {
            throw new OmsBaseException(OrderFailConsts.FAIL_DATA_CHANGE_ORDER_STATUS, "工单不在进行中");
        }

        // 计价器3.0不判断产品重复
        if (Objects.equals(orderWork.getServItemType(), OrderConsts.SERVICE_ITEM_TYPE_QUOTATION_THREE)) {
            // TODO 计价器3.0不校验相同产品
        } else if (Objects.equals(orderWork.getProductId(), modifyProductDTO.getProductId())) {
            throw new OmsBaseException("产品相同");
        }

        if (NumberUtil.isNotNullOrZero(orderWork.getOriginalAmount())) {
            OrderMember orderMember = orderMemberService.findMemberByKey(orderWork.getOrderId());
            if (!Objects.isNull(orderMember)) {
                if (Objects.equals(orderMember.getReviewStatus(), OrderConsts.ORDER_MEMBER_REVIEW_STATUS_WAIT_PLAT) && Objects
                        .equals(orderMember.getReviewResult(), OrderConsts.ORDER_MEMBER_REVIEW_RESULT_DOING)) {
                    throw new OmsBaseException("工单需后台延保复审,不可操作");
                }
                boolean reviewSuccess = orderMember.getReviewStatus() == OrderConsts.ORDER_MEMBER_REVIEW_STATUS_PLAT_SUCCESS;
                if (reviewSuccess) {
                    throw new OmsBaseException("工单为审核通过的延保订单，无法操作");
                }
            }
        }

        // 校验工程师修改产品的次数
        if (!Objects.equals(orderWork.getServItemType(), OrderConsts.SERVICE_ITEM_TYPE_QUOTATION_THREE)) {
            int masterModifyCount = 0;
            String key = String.format(RedisKeyConsts.MASTER_MODIFY_PRODUCT_COUNT_KEY, modifyProductDTO.getWorkId());
            String value = redisManager.get(key);
            if (StringUtil.isNotBlank(value)) {
                masterModifyCount = Integer.valueOf(value);
            }
            if (masterModifyCount >= MASTER_MODIFY_PRODUCT_COUNT) {
                throw new OmsBaseException("修改次数已达上限");
            }

            // 保存修改计数,如果是添加、修改，都计数
            redisManager.setex(key, String.valueOf(++masterModifyCount), MASTER_MODIFY_PRODUCT_COUNT_SECOND);
        }

        // 修改产品
        updateProduct(modifyProductDTO, orderWork);

        if (Objects.equals(orderWork.getServItemType(), OrderConsts.SERVICE_ITEM_TYPE_QUOTATION_THREE)) {
            // 计价器订单更新产品选择状态
            OrderQuotationProcess process = new OrderQuotationProcess();
            process.setOrderId(modifyProductDTO.getOrderId());
            process.setCheckProductStatus(GlobalConsts.YES);
            process.setCreater(modifyProductDTO.getOperator());
            process.setUpdater(modifyProductDTO.getOperator());
            process.setCreateTime(DateUtil.getNow());
            process.setUpdateTime(DateUtil.getNow());
            orderQuotationProcessService.updateByOrderIdSelectiveSrcMaster(process);
        }
    }
    /**
     * 工程师修改工单产品
     *
     * @param modifyProductDTO
     */
    @Override
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_MODIFY_PRODUCT, beforeProceed = false)
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderSaleProductByMaster(ModifyProductDTO modifyProductDTO) throws OmsBaseException {
        OrderWork orderWork = orderWorkService.findMasterWorkDetail(modifyProductDTO.getOrderId(),
                modifyProductDTO.getWorkId(), modifyProductDTO.getMasterId());
        if (orderWork == null) {
            throw new OmsBaseException(OrderFailConsts.FAIL_DATA_CHANGE_ORDER_NOMASTER, "无效的工单");
        }

        if (Objects.equals(orderWork.getStatus(), OrderStatusConsts.WORK_STATUS_COMPLETE) ||
                !Objects.equals(orderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_DOING)) {
            throw new OmsBaseException(OrderFailConsts.FAIL_DATA_CHANGE_ORDER_STATUS, "工单不在进行中");
        }

        // 计价器3.0不判断产品重复
        if (Objects.equals(orderWork.getProductId(), modifyProductDTO.getProductId())) {
            throw new OmsBaseException("产品相同");
        }

        if (NumberUtil.isNotNullOrZero(orderWork.getOriginalAmount())) {
            OrderMember orderMember = orderMemberService.findMemberByKey(orderWork.getOrderId());
            if (!Objects.isNull(orderMember)) {
                if (Objects.equals(orderMember.getReviewStatus(), OrderConsts.ORDER_MEMBER_REVIEW_STATUS_WAIT_PLAT) && Objects
                        .equals(orderMember.getReviewResult(), OrderConsts.ORDER_MEMBER_REVIEW_RESULT_DOING)) {
                    throw new OmsBaseException("工单需后台延保复审,不可操作");
                }
                boolean reviewSuccess = orderMember.getReviewStatus() == OrderConsts.ORDER_MEMBER_REVIEW_STATUS_PLAT_SUCCESS;
                if (reviewSuccess) {
                    throw new OmsBaseException("工单为审核通过的延保订单，无法操作");
                }
            }
        }

        // 修改产品
        updateSaleProduct(modifyProductDTO, orderWork);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderProductBrandByMaster(ModifyProductDTO modifyProductDTO) throws OmsBaseException {
        List<OrderProduct> orderProducts = orderProductService.listOrderProductByOrderId(modifyProductDTO.getOrderId());

        ResponseDTO<BrandDRO> responseDTO = brandListRemoteService.getById(modifyProductDTO.getBrandId());
        if (!responseDTO.isSuccess() || Objects.isNull(responseDTO.getData())) {
            log.error("获取品牌信息错误， 入参：{}, 出参：{}", modifyProductDTO.getBrandId(), JSON.toJSONString(responseDTO));
            throw new OmsBaseException("无法获取品牌信息，请稍后重试");
        }

        OrderProduct updateProduct = new OrderProduct();
        updateProduct.setProId(orderProducts.get(0).getProId());
        updateProduct.setBrandId(modifyProductDTO.getBrandId());
        updateProduct.setBrandName(responseDTO.getData().getName());
        updateProduct.setUpdateTime(DateUtil.getNow());
        orderProductService.updateBrandByKey(updateProduct);
    }

    /**
     * 修改工单产品
     *
     * @param modifyProductDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderProduct(ModifyProductDTO modifyProductDTO) throws OmsBaseException {
        OrderWork orderWork = orderWorkService.findMasterWorkDetail(modifyProductDTO.getOrderId(),
                modifyProductDTO.getWorkId(), modifyProductDTO.getMasterId());
        if (orderWork == null) {
            throw new OmsBaseException(OrderFailConsts.FAIL_DATA_CHANGE_ORDER_NOMASTER, "无效的工单");
        }

        if (Objects.equals(orderWork.getStatus(), OrderStatusConsts.WORK_STATUS_COMPLETE) ||
                !Objects.equals(orderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_DOING)) {
            throw new OmsBaseException(OrderFailConsts.FAIL_DATA_CHANGE_ORDER_STATUS, "工单不在进行中");
        }

        if (Objects.equals(orderWork.getProductId(), modifyProductDTO.getProductId())) {
            throw new OmsBaseException("产品相同");
        }

        // 修改产品
        updateProduct(modifyProductDTO, orderWork);
    }


    @Override
    public String checkUpdateProduct(ModifyProductDTO modifyProductDTO) {
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(modifyProductDTO.getOrderId(), modifyProductDTO.getWorkId());

        // 会员单 保内单
        if (Objects.equals(orderWork.getMember(), GlobalConsts.YES) || Objects.equals(orderWork.getBizType(), com.zmn.consts.GlobalConsts.BIZ_TYPE_F)) {
            return "该订单暂时不支持修改，请联系派单员";
        }

        String key = String.format(RedisKeyConsts.MASTER_MODIFY_PRODUCT_COUNT_KEY, modifyProductDTO.getWorkId());
        String value = redisManager.get(key);
        int count = 0;

        if (StringUtil.isNotBlank(value)) {
            count = Integer.valueOf(value);
        }
        if (count >= MASTER_MODIFY_PRODUCT_COUNT) {
            return "已超过修改上限，请联系派单员";
        }
        return "";
    }

    /**
     * 重置修改产品次数
     *
     * @param workId
     */
    @Override
    public void resetUpdateProductCount(Long workId) {
        String key = String.format(RedisKeyConsts.MASTER_MODIFY_PRODUCT_COUNT_KEY, workId);
        redisManager.del(key);
    }

    /**
     * 修改订单产品
     *
     * @param modifyProductDTO
     * @param orderWork
     * @throws OmsBaseException
     */
    private void updateProduct(ModifyProductDTO modifyProductDTO, OrderWork orderWork) throws OmsBaseException {
        log.info("{}修改订单产品 modifyProductDTO={}", orderWork.getWorkId(), modifyProductDTO);
        if (NumberUtil.isNullOrZero(modifyProductDTO.getProductId())) {
            throw new OmsBaseException("产品不存在");
        }

//        // 检验是否能修改墙面订单
//        wallQuotationBService.checkUpdateWallOrder(PilotCheckQuery.builder()
//                .categId(orderWork.getShowCategId())
//                .channelId(orderWork.getChannelId())
//                .cityId(orderWork.getCityId())
//                .servCategId(orderWork.getServCategId())
//                .pilotTypeId(PilotTypeEnum.WALL_QUOTE.getId())
//                .build(),orderWork.getProductGroupId(),orderWork.getServItemType(),orderWork.getWorkId());

        // 确定修改产品后，订单是否满足计价器类型
        CheckQuotationTypeOrderDTO checkQuotationTypeOrderDTO = CheckQuotationTypeOrderDTO.builder()
                .platWork(orderWork.getPlatWork())
                .channelId(orderWork.getChannelId())
                .cityId(orderWork.getCityId())
                .showProductId(orderWork.getShowProductId())
                .bizType(orderWork.getBizType())
                .type(orderWork.getType())
                .sourceType(orderWork.getSourceType())
                .productId(modifyProductDTO.getProductId())
                .companyId(orderWork.getCompanyId())
                .masterId(orderWork.getMasterId())
                .beforeServItemType(orderWork.getServItemType())
                .tariffType(modifyProductDTO.getTariffType())
                .build();
        
        Integer servItemType = servItemBService.getServItemType(checkQuotationTypeOrderDTO);
        Integer finalPrice = orderWork.getFinalPrice();
        log.info("{}修改产品前 servItemType={},finalPrice={}", orderWork.getWorkId(), orderWork.getServItemType(), orderWork.getFinalPrice());
        // servItemType==5的修改成4，并且标识一口价（一口价订单需求兼容app走计价器3.0流程）
        if (Objects.equals(servItemType, OrderConsts.SERVICE_ITEM_TYPE_FINAL_PRICE)) {
            servItemType = OrderConsts.SERVICE_ITEM_TYPE_QUOTATION_THREE;
            finalPrice = GlobalConsts.YES;
        } else {
            finalPrice = GlobalConsts.NO;
        }
        log.info("{}修改产品后 servItemType={},finalPrice={}", orderWork.getWorkId(), servItemType, finalPrice);
        modifyProductDTO.setServItemType(servItemType);

        ProductBaseQuery productDIO = new ProductBaseQuery();
        productDIO.setProductId(modifyProductDTO.getProductId());
        log.info("#order#modifyProduct 根据产品ID查询产品 入参: {}", productDIO);
        ResponseDTO<List<ProductBaseDRO>> responseDTO = productForeignListRemoteService.listBaseDROByQuery(productDIO);
        log.info("#order#modifyProduct 根据产品ID查询产品 出参: {}", JSON.toJSONString(responseDTO));

        if (!responseDTO.isSuccess()) {
            throw new OmsBaseException("获取新产品信息出错");
        }
        ProductBaseDRO productBaseDRO = responseDTO.getData().get(0);

        List<OrderProduct> productList = orderProductService.listOrderProductByOrderId(modifyProductDTO.getOrderId());
        Integer oldProductId = productList.get(0).getProductId();

        // 处理品牌信息
        Integer brandId = productList.get(0).getBrandId();
        String brandName = productList.get(0).getBrandName();
        // 处理品牌 如果有的话
        if (NumberUtil.isNotNullOrZero(modifyProductDTO.getBrandId())) {
            log.info("#order#modifyProduct 根据品牌ID查询产品 入参: {}", productDIO);
            ResponseDTO<BrandDRO> brandResponseDTO = brandListRemoteService.getById(modifyProductDTO.getBrandId());
            log.info("#order#modifyProduct 根据品牌ID查询产品 出参: {}", JSON.toJSONString(responseDTO));

            if (!responseDTO.isSuccess()) {
                throw new OmsBaseException("获取品牌信息出错");
            }

            BrandDRO brandDRO = brandResponseDTO.getData();
            brandId = brandDRO.getBrandId();
            brandName = brandDRO.getName();
        }

        String productInfo = String.format("%s-%s*%s", StringUtils.defaultString(brandName), productBaseDRO.getProductName(), productList.get(0).getNumber());

        // 设置log信息
        OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(modifyProductDTO.getOrderId());

        modifyProductDTO.setOldProductInfo(Optional.ofNullable(orderDetail.getProductInfo()).orElse("无"));
        modifyProductDTO.setNewProductInfo(productInfo);

        // 保存新的product
        OrderWork updateOrderWork = new OrderWork();
        updateOrderWork.setWorkId(modifyProductDTO.getWorkId());
        updateOrderWork.setOrderId(modifyProductDTO.getOrderId());
        updateOrderWork.setProductId(modifyProductDTO.getProductId());
        updateOrderWork.setCategOneId(productBaseDRO.getCategOneId());
        updateOrderWork.setCategId(productBaseDRO.getCategId());
        updateOrderWork.setProductGroupId(Optional.ofNullable(productBaseDRO.getFicoCategId()).orElse(0));
        if (!Objects.equals(servItemType, orderWork.getServItemType())) {
            updateOrderWork.setServItemType(servItemType);
        }
        if (!Objects.equals(finalPrice, orderWork.getFinalPrice())) {
            updateOrderWork.setFinalPrice(finalPrice);
        }

        // 后台产品分组
        log.info("servAssCategoryListRemoteService#getProductGroupByCategId 订单【{}】查询产品分组 入参：servCateg={}, categTwoId={}, bizType={}", orderWork.getOrderId(), productBaseDRO.getServCategId(), productBaseDRO.getCategId(), orderWork.getBizType());
        CategProductGroupQuery categProductGroupQuery = new CategProductGroupQuery();
        categProductGroupQuery.setServCategId(productBaseDRO.getServCategId());
        categProductGroupQuery.setCategId(productBaseDRO.getCategId());
        categProductGroupQuery.setBizType(orderWork.getBizType());
        categProductGroupQuery.setShowType(BaseProductConsts.ERP_SHOW_TYPE);
        ResponseDTO<CategProductGroupDRO> categoryProductGroupDROResponseDTO = categServProductListRemoteService.getBasisProductGroupByQuery(categProductGroupQuery);
        log.info("servAssCategoryListRemoteService#getProductGroupByCategId 订单【{}】查询产品分组 出参：【{}】", orderWork.getOrderId(), categoryProductGroupDROResponseDTO);

        CategProductGroupDRO categorySimpleProductGroupDRO = categoryProductGroupDROResponseDTO.getData();
        if (categorySimpleProductGroupDRO != null) {
            updateOrderWork.setServProductGroupId(categorySimpleProductGroupDRO.getGroupId());
            updateOrderWork.setServProductGroupName(categorySimpleProductGroupDRO.getName());
            updateOrderWork.setBizLine(categorySimpleProductGroupDRO.getBizLine());
        } else {
            updateOrderWork.setServProductGroupId(0);
            updateOrderWork.setServProductGroupName("");
            updateOrderWork.setBizLine(0);
        }

        orderWorkService.updateProductIdByKey(updateOrderWork);


        OrderProduct orderProduct = productList.get(0);

        // 处理价格表id
        OrderProduct updateProductTariffId = new OrderProduct();
        if (Objects.equals(productBaseDRO.getShowType(), BaseProductConsts.ERP_SHOW_TYPE)) {
            updateProductTariffId.setProductId(productBaseDRO.getProductId());
        } else {
            updateProductTariffId.setShowProductId(productBaseDRO.getProductId());
        }
        List<OrderProduct> orderProductList = Lists.newArrayList(updateProductTariffId);
        ProductTaraiffIdDTO productTaraiffIdDTO = ProductTaraiffIdDTO
                .builder()
                .orderProductList(orderProductList)
                .bizType(orderWork.getBizType())
                .cityId(orderWork.getCityId())
                .channelId(orderWork.getChannelId())
                .tariffType(modifyProductDTO.getTariffType())
                .build();
        servItemBService.processProductTaraiffId(productTaraiffIdDTO);
        updateProductTariffId = orderProductList.get(0);
        updateProductTariffId.setProId(orderProduct.getProId());
        updateProductTariffId.setOrderId(orderProduct.getOrderId());
        orderProductService.updateTariffIdByKey(updateProductTariffId);

        // 更新产品
        orderProduct.setProductId(productBaseDRO.getProductId());
        orderProduct.setProductName(productBaseDRO.getProductName());
        orderProduct.setCategOneId(productBaseDRO.getCategOneId());
        orderProduct.setCategOneName(productBaseDRO.getCategOneName());
        orderProduct.setCategId(productBaseDRO.getCategId());
        orderProduct.setCategName(productBaseDRO.getCategName());
        orderProduct.setBrandId(brandId);
        orderProduct.setBrandName(brandName);

        orderProductService.updateProductIdByKey(orderProduct);

        // 更新产品展开信息
        OrderProductExtend updateOrderProductExtend = new OrderProductExtend();
        updateOrderProductExtend.setOrderId(orderWork.getOrderId());
        updateOrderProductExtend.setOldProductId(oldProductId);
        updateOrderProductExtend.setProductId(orderProduct.getProductId());
        updateOrderProductExtend.setProductName(orderProduct.getProductName());
        orderProductExtendBService.updateByOrderIdAndOldProductId(updateOrderProductExtend);

        // 更新工单详情
        OrderDetail updateOrderDetail = new OrderDetail();
        updateOrderDetail.setDetailId(orderWork.getOrderId());
        updateOrderDetail.setProductGroupId(Optional.ofNullable(productBaseDRO.getFicoCategId()).orElse(0));
        updateOrderDetail.setProductGroupName(Optional.ofNullable(productBaseDRO.getFicoCategName()).orElse(""));
        updateOrderDetail.setProductId(productBaseDRO.getProductId());
        updateOrderDetail.setCategOneId(productBaseDRO.getCategOneId());
        updateOrderDetail.setCategId(productBaseDRO.getCategId());
        updateOrderDetail.setProductInfo(productInfo);
        orderDetailService.updateOrderDetailByKey(updateOrderDetail);

        // 清空订单优惠相关信息
        zsCustomWorkBService.updateProduct(modifyProductDTO, orderWork);

        // 设置默认服务项 - 一口价服务项目 - 清洗默认服务项
        OrderWork newOrderWork = orderWorkService.findOrderWorkByKeySrcMaster(orderWork.getOrderId(), orderWork.getWorkId());
        orderServiceItemBService.resetServiceItemByUpdate(newOrderWork);

        // 设置操作日志log信息
        MasterWorking masterWorking = masterWorkingService.findMasterWorkingByWorkId(orderWork.getWorkId());
        if (Objects.isNull(masterWorking)) {
            return;
        }
        modifyProductDTO.setOldProductInfo(Optional.ofNullable(masterWorking.getProductInfo()).orElse("无"));
        modifyProductDTO.setNewProductInfo(productInfo);

        // 保存新的productInfo到进行中工单表
        MasterWorking updateMasterWorking = new MasterWorking();
        updateMasterWorking.setWorkId(modifyProductDTO.getWorkId());
        updateMasterWorking.setProductInfo(productInfo);
        if (updateOrderWork.getServItemType() != null) {
            updateMasterWorking.setServItemType(updateOrderWork.getServItemType());
        }
        if (updateOrderWork.getFinalPrice() != null) {
            updateMasterWorking.setFinalPrice(updateOrderWork.getFinalPrice());
        }
        masterWorkingService.updateMasterWorking(updateMasterWorking);
    }

     /**
     * 修改订单销售产品
     * @param modifyProductDTO
     * @param orderWork
     * @throws OmsBaseException
     */
    private void updateSaleProduct(ModifyProductDTO modifyProductDTO, OrderWork orderWork) throws OmsBaseException {
        log.info("{}修改订单产品 modifyProductDTO={}", orderWork.getWorkId(), modifyProductDTO);
        if (NumberUtil.isNullOrZero(modifyProductDTO.getProductId())) {
            throw new OmsBaseException("产品不存在");
        }

//        // 检验是否能修改墙面订单
//        wallQuotationBService.checkUpdateWallOrder(PilotCheckQuery.builder()
//                .categId(orderWork.getShowCategId())
//                .channelId(orderWork.getChannelId())
//                .cityId(orderWork.getCityId())
//                .servCategId(orderWork.getServCategId())
//                .pilotTypeId(PilotTypeEnum.WALL_QUOTE.getId())
//                .build(),orderWork.getProductGroupId(),orderWork.getServItemType(),orderWork.getWorkId());

        // 确定修改产品后，订单是否满足计价器类型
        CheckQuotationTypeOrderDTO checkQuotationTypeOrderDTO = CheckQuotationTypeOrderDTO.builder()
                .platWork(orderWork.getPlatWork())
                .channelId(orderWork.getChannelId())
                .cityId(orderWork.getCityId())
                .showProductId(orderWork.getShowProductId())
                .bizType(orderWork.getBizType())
                .type(orderWork.getType())
                .sourceType(orderWork.getSourceType())
                .productId(modifyProductDTO.getProductId())
                .companyId(orderWork.getCompanyId())
                .masterId(orderWork.getMasterId())
                .beforeServItemType(orderWork.getServItemType())
                .tariffType(modifyProductDTO.getTariffType())
                .build();
        
        Integer servItemType = servItemBService.getServItemType(checkQuotationTypeOrderDTO);
        Integer finalPrice = orderWork.getFinalPrice();
        log.info("{}修改产品前 servItemType={},finalPrice={}", orderWork.getWorkId(), orderWork.getServItemType(), orderWork.getFinalPrice());
        // servItemType==5的修改成4，并且标识一口价（一口价订单需求兼容app走计价器3.0流程）
        if (Objects.equals(servItemType, OrderConsts.SERVICE_ITEM_TYPE_FINAL_PRICE)) {
            servItemType = OrderConsts.SERVICE_ITEM_TYPE_QUOTATION_THREE;
            finalPrice = GlobalConsts.YES;
        } else {
            finalPrice = GlobalConsts.NO;
        }
        log.info("{}修改产品后 servItemType={},finalPrice={}", orderWork.getWorkId(), servItemType, finalPrice);
        modifyProductDTO.setServItemType(servItemType);

        ProductBaseQuery productDIO = new ProductBaseQuery();
        productDIO.setProductId(modifyProductDTO.getProductId());
        log.info("#order#modifyProduct 根据产品ID查询产品 入参: {}", productDIO);
        ResponseDTO<List<ProductBaseDRO>> responseDTO = productForeignListRemoteService.listBaseDROByQuery(productDIO);
        log.info("#order#modifyProduct 根据产品ID查询产品 出参: {}", JSON.toJSONString(responseDTO));

        if (!responseDTO.isSuccess()) {
            throw new OmsBaseException("获取新产品信息出错");
        }
        ProductBaseDRO productBaseDRO = responseDTO.getData().get(0);

         // 获取对应前台产品
        DefaultEcProductQuery defaultEcProductQuery = new DefaultEcProductQuery();
        defaultEcProductQuery.setProductIdList(Lists.newArrayList(modifyProductDTO.getProductId()));
        defaultEcProductQuery.setShowType(BaseProductConsts.EC_SHOW_TYPE);
        ResponseDTO<List<ProductBaseDRO>> showProductRemote = productForeignListRemoteService.listEcErpProductByQuery(defaultEcProductQuery);
        if (!showProductRemote.isSuccess() || CollectionUtil.isNullOrEmpty(showProductRemote.getData())) {
            log.info("获取前台产品 入参：{}  出参：{}", JSON.toJSONString(defaultEcProductQuery), JSON.toJSONString(showProductRemote));
            throw new OmsBaseException("获取前台产品信息失败");
        }

        ProductBaseDRO showProduct = showProductRemote.getData().get(0);

        // 如果不是新机销售产品，不能修改
        if (!Objects.equals(ProductConsts.SERV_CATE_ID_GOODS_SALE, showProduct.getServCategId())) {
            throw new OmsBaseException("非新机销售产品，不可修改");
        }

        List<OrderProduct> productList = orderProductService.listOrderProductByOrderId(modifyProductDTO.getOrderId());
        Integer oldProductId = productList.get(0).getProductId();

        // 处理品牌信息
        Integer brandId = 1051;
        String brandName = "其他品牌";

        String productInfo = String.format("%s-%s*%s", StringUtils.defaultString(brandName), productBaseDRO.getProductName(), productList.get(0).getNumber());

        // 设置log信息
        OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(modifyProductDTO.getOrderId());

        modifyProductDTO.setOldProductInfo(Optional.ofNullable(orderDetail.getProductInfo()).orElse("无"));
        modifyProductDTO.setNewProductInfo(productInfo);

        // 保存新的product
        OrderWork updateOrderWork = new OrderWork();
        updateOrderWork.setWorkId(modifyProductDTO.getWorkId());
        updateOrderWork.setOrderId(modifyProductDTO.getOrderId());
        updateOrderWork.setProductId(modifyProductDTO.getProductId());
        updateOrderWork.setServCategId(showProduct.getServCategId());
        updateOrderWork.setCategOneId(productBaseDRO.getCategOneId());
        updateOrderWork.setCategId(productBaseDRO.getCategId());

        updateOrderWork.setShowProductId(showProduct.getProductId());
        updateOrderWork.setShowCategOneId(showProduct.getCategOneId());
        updateOrderWork.setShowCategId(showProduct.getCategId());
        updateOrderWork.setShowServCategName(showProduct.getServCategName());

        updateOrderWork.setProductGroupId(Optional.ofNullable(productBaseDRO.getFicoCategId()).orElse(0));
        if (!Objects.equals(servItemType, orderWork.getServItemType())) {
            updateOrderWork.setServItemType(servItemType);
        }
        if (!Objects.equals(finalPrice, orderWork.getFinalPrice())) {
            updateOrderWork.setFinalPrice(finalPrice);
        }

        // 后台产品分组
        log.info("servAssCategoryListRemoteService#getProductGroupByCategId 订单【{}】查询产品分组 入参：servCateg={}, categTwoId={}, bizType={}", orderWork.getOrderId(), productBaseDRO.getServCategId(), productBaseDRO.getCategId(), orderWork.getBizType());
        CategProductGroupQuery categProductGroupQuery = new CategProductGroupQuery();
        categProductGroupQuery.setServCategId(productBaseDRO.getServCategId());
        categProductGroupQuery.setCategId(productBaseDRO.getCategId());
        categProductGroupQuery.setBizType(orderWork.getBizType());
        categProductGroupQuery.setShowType(BaseProductConsts.ERP_SHOW_TYPE);
        ResponseDTO<CategProductGroupDRO> categoryProductGroupDROResponseDTO = categServProductListRemoteService.getBasisProductGroupByQuery(categProductGroupQuery);
        log.info("servAssCategoryListRemoteService#getProductGroupByCategId 订单【{}】查询产品分组 出参：【{}】", orderWork.getOrderId(), categoryProductGroupDROResponseDTO);

        CategProductGroupDRO categorySimpleProductGroupDRO = categoryProductGroupDROResponseDTO.getData();
        if (categorySimpleProductGroupDRO != null) {
            updateOrderWork.setServProductGroupId(categorySimpleProductGroupDRO.getGroupId());
            updateOrderWork.setServProductGroupName(categorySimpleProductGroupDRO.getName());
            updateOrderWork.setBizLine(categorySimpleProductGroupDRO.getBizLine());
        } else {
            updateOrderWork.setServProductGroupId(0);
            updateOrderWork.setServProductGroupName("");
            updateOrderWork.setBizLine(0);
        }

        orderWorkService.updateProductIdByKey(updateOrderWork);


        OrderProduct orderProduct = productList.get(0);

        // 处理价格表id
        OrderProduct updateProductTariffId = new OrderProduct();
        if (Objects.equals(productBaseDRO.getShowType(), BaseProductConsts.ERP_SHOW_TYPE)) {
            updateProductTariffId.setProductId(productBaseDRO.getProductId());
        } else {
            updateProductTariffId.setShowProductId(productBaseDRO.getProductId());
        }
        List<OrderProduct> orderProductList = Lists.newArrayList(updateProductTariffId);
        ProductTaraiffIdDTO productTaraiffIdDTO = ProductTaraiffIdDTO
                .builder()
                .orderProductList(orderProductList)
                .bizType(orderWork.getBizType())
                .cityId(orderWork.getCityId())
                .channelId(orderWork.getChannelId())
                .tariffType(modifyProductDTO.getTariffType())
                .build();
        servItemBService.processProductTaraiffId(productTaraiffIdDTO);
        updateProductTariffId = orderProductList.get(0);
        updateProductTariffId.setProId(orderProduct.getProId());
        updateProductTariffId.setOrderId(orderProduct.getOrderId());
        orderProductService.updateTariffIdByKey(updateProductTariffId);

        // 更新产品
        orderProduct.setProductId(productBaseDRO.getProductId());
        orderProduct.setProductName(productBaseDRO.getProductName());
        orderProduct.setCategOneId(productBaseDRO.getCategOneId());
        orderProduct.setCategOneName(productBaseDRO.getCategOneName());
        orderProduct.setCategId(productBaseDRO.getCategId());
        orderProduct.setCategName(productBaseDRO.getCategName());
        orderProduct.setBrandId(brandId);
        orderProduct.setBrandName(brandName);

        orderProduct.setShowProductId(showProduct.getProductId());
        orderProduct.setShowProductName(showProduct.getProductName());

        orderProductService.updateProductIdByKey(orderProduct);

        // 更新产品展开信息
        OrderProductExtend updateOrderProductExtend = new OrderProductExtend();
        updateOrderProductExtend.setOrderId(orderWork.getOrderId());
        updateOrderProductExtend.setOldProductId(oldProductId);
        updateOrderProductExtend.setProductId(orderProduct.getProductId());
        updateOrderProductExtend.setProductName(orderProduct.getProductName());
        updateOrderProductExtend.setShowProductId(showProduct.getProductId());
        updateOrderProductExtend.setShowProductName(showProduct.getProductName());
        orderProductExtendBService.updateByOrderIdAndOldProductId(updateOrderProductExtend);

        // 更新工单详情
        OrderDetail updateOrderDetail = new OrderDetail();
        updateOrderDetail.setDetailId(orderWork.getOrderId());
        updateOrderDetail.setProductGroupId(Optional.ofNullable(productBaseDRO.getFicoCategId()).orElse(0));
        updateOrderDetail.setProductGroupName(Optional.ofNullable(productBaseDRO.getFicoCategName()).orElse(""));
        updateOrderDetail.setProductId(productBaseDRO.getProductId());
        updateOrderDetail.setCategOneId(productBaseDRO.getCategOneId());
        updateOrderDetail.setCategId(productBaseDRO.getCategId());
        updateOrderDetail.setProductInfo(productInfo);

        updateOrderDetail.setServCategId(showProduct.getServCategId());
        updateOrderDetail.setServCategName(showProduct.getServCategName());

        orderDetailService.updateOrderDetailByKey(updateOrderDetail);

        // 清空订单优惠相关信息
        zsCustomWorkBService.updateProduct(modifyProductDTO, orderWork);

        // 设置默认服务项 - 一口价服务项目 - 清洗默认服务项
        OrderWork newOrderWork = orderWorkService.findOrderWorkByKeySrcMaster(orderWork.getOrderId(), orderWork.getWorkId());
        orderServiceItemBService.resetServiceItemByUpdate(newOrderWork);

        // 设置操作日志log信息
        MasterWorking masterWorking = masterWorkingService.findMasterWorkingByWorkId(orderWork.getWorkId());
        if (Objects.isNull(masterWorking)) {
            return;
        }
        modifyProductDTO.setOldProductInfo(Optional.ofNullable(masterWorking.getProductInfo()).orElse("无"));
        modifyProductDTO.setNewProductInfo(productInfo);

        // 保存新的productInfo到进行中工单表
        MasterWorking updateMasterWorking = new MasterWorking();
        updateMasterWorking.setWorkId(modifyProductDTO.getWorkId());
        updateMasterWorking.setProductInfo(productInfo);
        if (updateOrderWork.getServItemType() != null) {
            updateMasterWorking.setServItemType(updateOrderWork.getServItemType());
        }
        if (updateOrderWork.getFinalPrice() != null) {
            updateMasterWorking.setFinalPrice(updateOrderWork.getFinalPrice());
        }
        masterWorkingService.updateMasterWorking(updateMasterWorking);

        // 更新记录
        ChangeServCategDTO dto = new ChangeServCategDTO();
        dto.setOrderId(modifyProductDTO.getOrderId());
        dto.setCurrServCategId(ProductConsts.SERV_CATE_ID_GOODS_SALE);
        dto.setOperateTime(DateUtil.getNow());
        dto.setOperatorId(modifyProductDTO.getOperatorId());
        dto.setOperatorName(modifyProductDTO.getOperator());
        dto.setOperatorType(modifyProductDTO.getOperatorType());
        orderChangeRecordService.updateChangeServCateg(dto);
    }

}
